from apps.accounts.models import User
from apps.master.filters import SerialNumberFilters, CurrencyRateFilters, DepartmentsFilters, CurrencyFilters
from apps.master.models import SerialNumberModel, CurrencyRateModel, DepartmentsModel, CurrencyModel
from apps.master.serializers import SerialNumberSerializer, CurrencyRateSerializer, DepartmentsSerializer, \
    CurrencySerializer
from bases.viewsets import APIModelViewSet
from rest_framework.views import APIView
from django.db import transaction
from bases.response import SuccessResponse


class SerialNumberViewSet(APIModelViewSet):
    queryset = SerialNumberModel.objects.all()
    serializer_class = SerialNumberSerializer
    filter_class = SerialNumberFilters

class SerialNumberByUserViewSet(APIModelViewSet):

    def get_queryset(self):
        current_user = self.request.user
        user_departments = current_user.departments.all()
        if user_departments:
            queryset = SerialNumberModel.objects.filter(serial_department__in=user_departments)
        else:
            queryset = SerialNumberModel.objects.all()
        return queryset

    serializer_class = SerialNumberSerializer

class CurrencyViewSet(APIModelViewSet):
    queryset = CurrencyModel.objects.all()
    serializer_class = CurrencySerializer
    filter_class = CurrencyFilters

class CurrencyRateViewSet(APIModelViewSet):
    queryset = CurrencyRateModel.objects.all()
    serializer_class = CurrencyRateSerializer
    filter_class = CurrencyRateFilters

class DepartmentsViewSet(APIModelViewSet):
    queryset = DepartmentsModel.objects.all()
    serializer_class = DepartmentsSerializer
    filter_class = DepartmentsFilters


class DepartmentsByUserViewSet(APIModelViewSet):

    def get_queryset(self):
        current_user = self.request.user
        user_departments = current_user.departments.all()
        if user_departments:
            queryset = DepartmentsModel.objects.filter(id__in=user_departments)
        else:
            queryset = DepartmentsModel.objects.all()
        return queryset

    serializer_class = DepartmentsSerializer

class DepartmentAssignUserViewSet(APIView):
    def get(self, request):
        department_id = request.GET.get('department')
        department = DepartmentsModel.objects.get(id=department_id)
        data = dict()
        un_assigned_list = []
        un_assigned_users = User.objects.values('name', 'id').filter(is_active=True).order_by('id')
        assigned_list = User.objects.values_list('id', flat=True).filter(departments=department).order_by('id')

        for un_assigned_user in un_assigned_users:
            un_assigned = dict()
            un_assigned['key'] = un_assigned_user['id']
            un_assigned['label'] = un_assigned_user['name']
            un_assigned_list.append(un_assigned)

        data['un_assigned'] = un_assigned_list
        data['assigned'] = list(assigned_list)

        return SuccessResponse(data)

    @transaction.atomic
    def post(self, request):
        department_id = request.data.get('department')
        user_id_list = request.data['user']

        department = DepartmentsModel.objects.get(id=department_id)

        department_users = department.departments.all()

        for user in department_users:
            user.departments.remove(department)

        for user_id in user_id_list:
            user = User.objects.get(id=user_id)
            user.departments.add(department)

        return SuccessResponse()


class DepartmentAssignSerialNumViewSet(APIView):

    def get(self, request):
        department_id = request.GET.get('department') # 前端传回的参数
        department = DepartmentsModel.objects.get(id=department_id) # 从前端传回的查询参数中获取部门对象
        data = dict() # 初始化一个空字典，用来盛放最终要返回的数据
        un_assigned_list = [] # 初始化一个空列表
        un_assigned_serialnum = SerialNumberModel.objects.values('serial_number', 'id').order_by('id') # 从制番model中获取所有制番数据，并按照id正序排序
        assigned_list = SerialNumberModel.objects.values_list('id', flat=True).filter(serial_department=department).order_by('id') # 从制番model中获取所有已经分配给指定部门的制番id，并按照id排序
        # 遍历未分配的制番数据，把每个数据转换成包含key和label的字典，并放到列表中
        for un_assigned_user in un_assigned_serialnum:
            un_assigned = dict()
            un_assigned['key'] = un_assigned_user['id']
            un_assigned['label'] = un_assigned_user['serial_number']
            un_assigned_list.append(un_assigned)

        data['un_assigned'] = un_assigned_list # 把所有的制番list赋给data字典的un_assigned键
        data['assigned'] = list(assigned_list) # 把已分配的list赋给data字典的assigned

        return SuccessResponse(data) # 返回包含data字典的成功响应

    @transaction.atomic
    def post(self, request):
        department_id = request.data.get('department') # 从前端传来的参数department
        serialnum_id_list = request.data['serialnum'] # 从前端传来的参数serialnum

        department = DepartmentsModel.objects.get(id=department_id) # 利用前端传来的参数获取部门对象

        department_users = department.serial_department.all()  # 获取当前部门已关联的所有序列号（通过反向关联 `serial_department`）
        # 第一步：移除部门与所有旧序列号的关联
        for serialnum in department_users:
            serialnum.serial_department.remove(department) # 从序列号的关联部门中移除当前部门

        # 第二步：添加部门与新序列号的关联
        for serialnum_id in serialnum_id_list:
            serialnum = SerialNumberModel.objects.get(id=serialnum_id)
            serialnum.serial_department.add(department) # 向序列号的关联部门中添加当前部门

        return SuccessResponse() # 返回成功响应
